package org.sample.springboot.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.sample.springboot.util.ReflectUtils;
import org.sample.springboot.util.ReflectUtils.ReflectResult;
import org.sample.springboot.validator.constraints.optional.provider.OptionalProvider;
import org.sample.springboot.validator.constraints.optional.provider.ProviderOptionalConstraint;

public class ProviderOptionalValidator extends OptionalValidator
		implements ConstraintValidator<ProviderOptionalConstraint, Object> {

	private Class<? extends OptionalProvider> providerClass;
	
	@Override
	public void initialize(ProviderOptionalConstraint constraintAnnotation) {
		providerClass = constraintAnnotation.provider();
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		if (value == null) {
			return true;
		}
		
		ReflectResult<? extends OptionalProvider> instanceResult = ReflectUtils.newInstance(providerClass);
		if (!instanceResult.isAvailable()){
			return false;
		}
		
		OptionalProvider provider = instanceResult.getResult();
		return isValid(provider.isEnabled(value), provider.getOptionalValue(value), provider.getOptionalFieldName(),
				context);
	}

}
